import webapp2
import jinja2
import os
import cgi
import string
import random

import datamodel
import mobile

from google.appengine.api import users

#google sessions http://code.google.com/p/gmemsess/
import gmemsess

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class MainPage(webapp2.RequestHandler):
    template = jinja_environment.get_template('index.html')
    template_values = {}
    def displayConsole(self, sess):
        qScoreBrd = datamodel.Application.all()
        qScoreBrd.filter("email =", sess['email'])

        qTnB = datamodel.TnBApplication.all()
        qTnB.filter("email =", sess['email'])

        self.template_values = {
            'username': sess['username'],
            'email': sess['email'],
            'recordsScoreBoard' :qScoreBrd.run(),
            'recordsTrynBuy' :qTnB.run()
                }
        self.template = jinja_environment.get_template('console.html')
        
    def get(self):
        sess = gmemsess.Session(self)
        user = users.get_current_user() 
        if not sess.is_new() :
            if sess['promocode'] == 'authenticated':
                self.displayConsole(sess)
            elif user and sess['promocode'] == 'passed':
                sess['username'] = user.nickname()
                sess['email'] = user.email()
                sess['promocode'] = 'authenticated'
                sess.save()
                self.displayConsole(sess)

        self.response.out.write(self.template.render(self.template_values))
    def post(self):
        sess = gmemsess.Session(self)
        promocode = cgi.escape(self.request.get('promocode'))

        authLogout = cgi.escape(self.request.get('authLogout'))
        
        appId = cgi.escape(self.request.get('appID'))

        if len(promocode) > 0 and promocode == 'testinput':
            sess['promocode'] = 'passed'
            sess.save()
            user = users.get_current_user()    
            if not user:
                return self.redirect(users.create_login_url(self.request.uri))
            elif user and sess['promocode'] == 'passed':
                sess['username'] = user.nickname()
                sess['email'] = user.email()
                sess['promocode'] = 'authenticated'
                sess.save()
                self.displayConsole(sess)
        elif len(authLogout) > 0 and authLogout == 'logout':
            sess.invalidate()
            ssologouturl = users.create_logout_url(self.request.uri)
            self.template_values = {
                'ssologouturl': ssologouturl
                    }
        elif len(appId) > 0 and sess['promocode'] == 'authenticated':
                self.template_values = {
                    'username': sess['username'],
                    'email': sess['email']
                        }
                self.template = jinja_environment.get_template('console.html')
                char_set = string.ascii_uppercase + string.digits
                random_string = ''.join(random.sample(char_set, 20))
                service = cgi.escape(self.request.get('appService'))
                if service == datamodel.services[1]:
                    datamodel.Application(key_name=random_string,
                                                username=sess['username'],
                                                email=sess['email'],
                                                appName = cgi.escape(self.request.get('appName')),
                                                appDescr = cgi.escape(self.request.get('appDescr')),
                                                appService = service,
                                                appKey = random_string,
                                                enabled = True
                                                ).put()
                elif service == datamodel.services[0]:
                    datamodel.TnBApplication(key_name=random_string,
                                                username=sess['username'],
                                                email=sess['email'],
                                                appName = cgi.escape(self.request.get('appName')),
                                                appDescr = cgi.escape(self.request.get('appDescr')),
                                                appService = service,
                                                appKey = random_string,
                                                enabled = True,
                                                tnbdurattion = 0,
                                                tnbunit = 'days',
                                                tnbtries = 3
                                                ).put()
                self.displayConsole(sess)
        self.response.out.write(self.template.render(self.template_values))
            
            

app = webapp2.WSGIApplication([(r'^/$', MainPage),
                               (r'^/mobile$', mobile.Dispatcher)],
                              debug=True)
